package com.zbkj.crmeb.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.RestTemplateUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.CommonStoreOrderService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 易镭订单推送
 * @author chenchongli
 * @date:  2024-04-15 11:49
 */
@Service("easyRadiumOrderServiceImpl")
@Slf4j
public class EasyRadiumOrderServiceImpl implements CommonStoreOrderService {

    @Autowired
    RestTemplateUtil restTemplateUtil;

    private final static String APIURL = "http://api.hiqlty.com/pub/order";
    private final static String APPKEY = "9UMF47WBSH9U5MMQU0W95N9L7GYR32VL"; //密钥
    private final static String PARTNERID = "58069385";


    /**
     * 订单推送
     * @param storeOrder
     * @param infos
     * @return
     */
    @Override
    public CommonResult pushOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> infos) {
        log.info("--------------- 公共仓收到订单推送接口请求, 订单号: {} ---------------", storeOrder.getOrderId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 构建请求参数
        JSONObject requestData = new JSONObject();
        requestData.put("partnerid", PARTNERID);

        // 业务信息
        requestData.put("orderNo", storeOrder.getOrderId());
        requestData.put("createTime", sdf.format(storeOrder.getCreateTime()));
        requestData.put("ShopName", "海客来");
        requestData.put("payAmount", storeOrder.getPayPrice());
        String company = "";
        if("weixin".equalsIgnoreCase(storeOrder.getPayType()) || "WECHAT".equalsIgnoreCase(storeOrder.getPayType())){
            company = "微信";
        }else if("alipay".equalsIgnoreCase(storeOrder.getPayType())){
            company = "支付宝";
        }
        requestData.put("payCompanyName", company);
        // 处理别样支付单号
        requestData.put("PayOrderNo", "BIE_YANG".equals(storeOrder.getRemark()) ? storeOrder.getPayNo() : storeOrder.getOutOrderId());
        requestData.put("payTime", sdf.format(storeOrder.getPayTime()));
        requestData.put("PurcName", storeOrder.getRealName());
        requestData.put("PurcPaperNumber", storeOrder.getIdCard());
        requestData.put("consignee", storeOrder.getCreateName());

        String phoneNumber = storeOrder.getUserPhone();
        // 通过正则表达式匹配可能的国际区号格式
        Pattern pattern = Pattern.compile("^(?:\\+\\d{1,3}[\\s-]?)?(\\d{10,})$");
        Matcher matcher = pattern.matcher(phoneNumber);
        if (matcher.matches()) {
            // 获取去除国际区号后的手机号
            phoneNumber = matcher.group(1);
        }
        requestData.put("consigneeTel", phoneNumber);
        requestData.put("Province", storeOrder.getProvince());
        requestData.put("city", storeOrder.getCity());
        requestData.put("area", storeOrder.getDistrict());
        requestData.put("address", storeOrder.getDetail());
        requestData.put("orderType", 0);
        requestData.put("note", storeOrder.getMark());

        // 商品信息
        JSONArray orderItems = new JSONArray();
        for (StoreOrderInfoVo info : infos) {
            JSONObject goods = new JSONObject();
            goods.put("itemNo", info.getInfo().getProductInfo().getBarCode());
            goods.put("itemQuantity", info.getInfo().getCartNum());
            goods.put("itemPrice", info.getPayPrice().movePointRight(2).toString());
            orderItems.add(goods);
        }
        requestData.put("orderItems", orderItems);
        log.info("--------易镭推单数据: {}---------", requestData);

        // 将requestData转换为JSON字符串
        String result = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            String jsonRequestData = new ObjectMapper().writeValueAsString(requestData);
            // 计算签名
            String content = APPKEY + jsonRequestData + APPKEY;
            String sign = DigestUtils.md5Hex(content).toUpperCase();
            // 请求头
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("sign", sign);

            // 创建HttpEntity对象，包含请求头和请求体
            HttpEntity<String> requests = new HttpEntity<>(jsonRequestData, headers);
            // 发送请求
            result = new RestTemplate().postForEntity(APIURL + "/receive", requests, String.class).getBody();
            log.info("--------------- 易镭订单推送接口返回, result: {} ---------------", result);
        }  catch (HttpClientErrorException | HttpServerErrorException e) {
            log.error("API请求失败, 状态码: ", e.getStatusCode());
            log.error("错误报文: " + e.getResponseBodyAsString());
        } catch (Exception e) {
            log.error("发生其他异常错误: " + e.getMessage());
        }

        JSONObject resultObj = JSON.parseObject(result);
        // 获取对应信息
        boolean isSuccess = resultObj.getBoolean("success");
        if(isSuccess) {
            log.info("--------------- 易镭订单推送成功, orderNo: {} ---------------", storeOrder.getOrderId());
            return CommonResult.success();
        } else {
            log.info("--------------- 易镭订单推送接口异常, message: {} ---------------", resultObj.getString("errorMsg"));
            return CommonResult.failed(resultObj.getString("message"));
        }
    }

    /**
     * 查询物流信息
     * @param orderNo
     * @return
     */
    @Override
    public JSONObject queryOrder(String orderNo) {
        log.info("--------------- 易镭收到订单查询接口请求, 订单号: {} ---------------", orderNo);

        JSONObject params = new JSONObject();
        params.put("partnerid", PARTNERID);
        params.put("orderno", orderNo);

        // 计算签名
        String content = APPKEY + params + APPKEY;
        String sign = DigestUtils.md5Hex(content).toUpperCase();
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("sign", sign);

        String result = restTemplateUtil.postFormData(APIURL + "/getwaybill", headers);

        log.info("--------------- 易镭订单查询接口返回, result: {} ---------------", result);
        JSONObject resultObj = JSON.parseObject(result);
        // 获取对应信息
        boolean isSuccess = resultObj.getBoolean("success");
        if(isSuccess) {
            JSONObject resultData = resultObj.getJSONObject("logisticsInfo");
            // (0,"待审核" 3,"待支付" 15,"清关中" 20,"清关完成" 30,"下发仓库" 40,"订单出库" 50,"订单取消" 100,"已完成")
//    		Integer orderInfoStatus = resultData.getInteger("orderInfoStatus"); // 订单状态
            // 圆通   YTO 韵达   YUNDA 中通  ZTO 顺丰  SF 邮政   YOUZHENG
//    		String expressId = resultData.getString("expressId"); // 快递简称
//    		String expressNo = resultData.getString("expressNo"); // 快递单号
//    		Integer intercept = resultData.getInteger("intercept"); // 拦截信息, 不为0代表被拦截

            return resultData;
        } else {
            log.info("--------------- 易镭订单查询接口异常, message: {} ---------------", resultObj.getString("errorMsg"));
        }

        return null;
    }
}
